package ReadCommit.connection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.text.SimpleDateFormat;


public class ReadCommitThread extends Thread implements ReadCommitSql {

    private static final Logger logger = LoggerFactory.getLogger(ReadCommitThread.class);

    private ConnectionInfo connectionInfo;

    public ReadCommitThread(ConnectionInfo connectionInfo) {
        this.connectionInfo = connectionInfo;
    }
    private int selectBalance(int id, Connection connection) throws SQLException {
        int result = 0;
        ResultSet resultSet;
        String randomId = getRandomId();
        try (Statement statement = connection.createStatement()){
             resultSet = statement.executeQuery("select balance as a"+ randomId  +" from account where transaction_id = "+ id +";");
             if (resultSet.next()) {
                 result = resultSet.getInt(1);
             }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
    public void run() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd hh:mm:ss:SSS");
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try (Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword());

            Statement s1 = connection.createStatement();
            Statement s2 = connection.createStatement()){
            connection.setAutoCommit(false);
            int balance1 = selectBalance(2, connection);
            System.out.println(sdf.format(new Date(System.currentTimeMillis())) + " " + Thread.currentThread() +" get balance from col2 " + balance1);
            logger.info("get balance from col2 " + balance1);
            s1.execute(decreaseAccountSql);


            int balance2 = selectBalance(1, connection);
            System.out.println(sdf.format(new Date(System.currentTimeMillis())) + " " + Thread.currentThread() +" get balance from col1 " + balance2);
            logger.info("get balance from col1 " + balance2);
            s2.execute(increaseAccountSql);
            connection.commit();
            System.out.println(new Date(System.currentTimeMillis()) + " " + Thread.currentThread() + " 提交事务");
            logger.info("提交事务");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
